package logic

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/vueadmin/app/admin/common/captcha"
	"github.com/vueadmin/app/admin/internal/dto"
	"github.com/vueadmin/app/admin/internal/model"
	"github.com/vueadmin/app/admin/internal/service"
	"github.com/vueadmin/app/admin/internal/svc"
	"github.com/vueadmin/pkg/jwt"
	"github.com/vueadmin/utils"
	"github.com/vueadmin/utils/conv"
	"strings"
)

type LoginLogic struct {
	ctx    *gin.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx *gin.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (p LoginLogic) Login(req *dto.LoginReq) (string, error) {
	if !captcha.Verify(p.svcCtx, req.CaptchaId, req.Captcha) {
		return "", errors.New("验证码错误!")
	}
	s := service.NewLoginService(p.svcCtx)
	info, err := s.Login(req)
	if err != nil {
		return "", err
	}
	info.Access = strings.Join(info.Role.Access, ",")
	token, jwtErr := jwt.NewJwt(conv.String(p.svcCtx.Config.Jwt)).CreateToken(info)
	if jwtErr != nil {
		return "", jwtErr
	}
	return token, nil
}

// 写入登录日志
func (p LoginLogic) CreateLoginLog(req *dto.LoginReq) {
	var data model.Log
	data.ApplicationName = "admin"
	data.Username = req.User
	data.Ip = utils.GetRemoteClientIp(p.ctx)
	data.Url = "http://" + p.ctx.Request.Host + p.ctx.Request.RequestURI
	data.Useragent = p.ctx.Request.UserAgent()
	data.Type = 1
	data.CreateTime = conv.NowUnix()

	if err := p.svcCtx.Db.Create(&data).Error; err != nil {
		p.svcCtx.Log.Error(err.Error())
	}
}
